package dailearn.producer.controller;

import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 *
 * @author daify
 * @date 2019-07-08 13:45
 **/
@RestController
public class FileUploadController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test()
            throws IOException {
        return "test";
    }

    @RequestMapping(value = "/testError", method = RequestMethod.GET)
    public String testError(){
        throw new RuntimeException("testError");
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) 
            throws IOException {
        byte[] bytes = file.getBytes();
        File fileToSave = new File(file.getOriginalFilename());
        FileCopyUtils.copy(bytes, fileToSave);
        return fileToSave.getAbsolutePath();
    }
}
